package com.rivues.module.design.web.handler.analytics;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.handler.Handler;
import com.rivues.module.platform.web.handler.ResponseData;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.AnalyzerReport;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.PublishedCube;
import com.rivues.module.platform.web.model.ReportFilter;
import com.rivues.module.report.web.handler.ReportHandler;
import com.rivues.module.report.web.model.PublishedReport;
import com.rivues.util.iface.cube.CubeFactory;
import com.rivues.util.iface.report.ReportFactory;
import com.rivues.util.local.LocalTools;
import com.rivues.util.serialize.JSON;
import com.rivues.util.service.cache.CacheHelper;
  
@Controller  
@RequestMapping("/{orgi}/design/analytics")  
public class AnalyticsController  extends ReportHandler{  
	private final Logger log = LoggerFactory.getLogger(LogIntercreptorHandler.class); 
    @RequestMapping(value="/index" , name="index" , type="design",subtype="analytics")
    public ModelAndView index(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
    	return request(super.createManageResponse("/pages/design/analytics/index") , orgi) ;
    }
    
//    @RequestMapping(value="/{reportid}" , name="design" , type="design",subtype="analytics")
//    public ModelAndView design(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
//    	return request(super.createManageResponse("/pages/design/analytics/analyzerdesign") , orgi) ;
//    }
//    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}" , name="analyticsdesign" , type="design",subtype="analytics")
    public ModelAndView analyticsdesign(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/analyzerdesign") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	AnalyzerReport analyzerReport = report.getReport();
    	/**
    	 * 以下代码用于 传递参数
    	 */
    	for(ReportFilter reportFilter : analyzerReport.getFilters()){
    		if(RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype())){
    			if(request.getParameter(reportFilter.getCode()+"_start")!=null && request.getParameter(reportFilter.getCode()+"_end")!=null){
	    			if(RivuDataContext.FilterConValueEnum.AUTO.toString().equals(reportFilter.getConvalue())){
	    				String start = request.getParameter(reportFilter.getCode()+"_start")!=null ? request.getParameter(reportFilter.getCode()+"_start") : "" ;
	    				String end = request.getParameter(reportFilter.getCode()+"_end")!=null ? request.getParameter(reportFilter.getCode()+"_end") : "" ;
	    				if((start.length() - start.replaceAll(".", "").length()) != (end.length() - end.replaceAll(".", "").length())){
	    					continue ;
	    				}
	    			}
	    			reportFilter.setRequeststartvalue(request.getParameter(reportFilter.getCode()+"_start")) ;
	    			reportFilter.setRequestendvalue(request.getParameter(reportFilter.getCode()+"_end")) ;
    			}
    		}else{
	    		if(request.getParameter(reportFilter.getCode())!=null){
	    			reportFilter.setRequestvalue(request.getParameter(reportFilter.getCode())) ;
	    		}
    		}
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , false) ;
    	/**
    	 * 创建视图
    	 */
    	/**
    	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    	 */
    	return createReportView(view , report , request);
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/modeladd" , name="modeladd" , type="design",subtype="analytics")
    public ModelAndView modeladd(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/modeladd") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	AnalyzerReport analyzerReport = report.getReport();
    	if(report!=null){
    		view.addObject("report",report);
    	}
    	view.addObject("analyzerReport",analyzerReport);
    	/**
    	 * 创建视图
    	 */
    	/**
    	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    	 */
    	return view;
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/modeladdo" , name="modeladdo" , type="design",subtype="analytics")
    public ModelAndView modeladdo(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @Valid AnalyzerReportModel model) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/template") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	
    	//图表页面未提供刷新缓存，所以直接将缓存置为false
//    	report.setCache(false);
    	AnalyzerReport analyzerReport = report.getReport();
    	
    	if(analyzerReport!=null){
			model.setId(String.valueOf(System.currentTimeMillis()));
			model.setOrgi(orgi);
			model.setDstype(RivuDataContext.CubeEnum.CUBE.toString()) ;
			model.setReportid(reportid);
			analyzerReport.getModel().add(model) ;
    	}
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , false) ;
    	/**
    	 * 创建视图
    	 */
    	/**
    	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    	 */
    	return createReportView(view , report , request);
    }
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/position" , name="position" , type="design",subtype="analytics")
    public ModelAndView position(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid, @Valid String dt) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/public/success") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		String[] dts = dt.split(";") ;
    		for(String data : dts){
    			String[] modelprop = data.split(",") ;
    			if(modelprop.length == 5){
    				String modelid = modelprop[0] ;
    				for(AnalyzerReportModel model : analyzerReport.getModel()){
    	    			if(model.getId().equals(modelid)){
    	    				reportModel = model ;
    	    				reportModel.setPosx(modelprop[1]) ;
    	    	    		reportModel.setPosy(modelprop[2]) ;
    	    	    		reportModel.setPoswidth(modelprop[3]);
    	    	    		reportModel.setPosheight(modelprop[4]) ;
    	    				break ;
    	    			}
    	    		}
    			}
    		}
    	}
		/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi) ;
    	
    	/**
    	 * 创建视图
    	 */
    	/**
    	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    	 */
    	return view;
    }
    
    @RequestMapping(value = "/{reportid}/{modelid}/reloadmodel", name="reloadmodel" , type="design",subtype="analytics")
   	public ModelAndView reloadmodel(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid ) throws Exception{
       	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
       	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/model") , orgi) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	AnalyzerReportModel reportModel = null ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				reportModel = model ;
    				break;
    			}
    		}
    	}
    	if(reportModel != null){
    		view = createModelAndView(view , true , report , request , reportModel);
    	}
    	
       	return  view;
   	}
    
    /**
     * 获取报表，使用设计器打开
     * @param request
     * @param orgi
     * @param reportid
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/{reportid}/savereport" , name="savereport" , type="design",subtype="analytics")
    public ModelAndView savereport(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid , @Valid String oid, @Valid String type) throws Exception{  
    	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/savereport") , orgi) ;
    	/**
    	 * 保存报表
    	 */
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request) , orgi, reportid);
    	if(report.getCreater()!=null && report.getCreater().equals(super.getUser(request).getId())){
	    	ReportFactory.getReportInstance().updateReport(report,super.getUser(request)) ;
	    	view.addObject("msg", LocalTools.getMessage("I_DESIGN_1000001")) ;
    	}else{
    		view.addObject("msg", LocalTools.getMessage("E_DESIGN_2000001")) ;
    	}
    	return view ;
    }
    
    @RequestMapping(value = "/{reportid}/{modelid}/deletemodel", name="deletemodel" , type="design",subtype="analytics")
   	public ModelAndView deletemodel(HttpServletRequest request , @PathVariable String  orgi , @PathVariable String  reportid,@PathVariable String  modelid ) throws Exception{
    	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/template") , orgi) ;
    	PublishedReport report = ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid) ;
    	AnalyzerReport analyzerReport = report.getReport() ;
    	if(analyzerReport.getModel().size()>0){
    		for(AnalyzerReportModel model : analyzerReport.getModel()){
    			if(model.getId().equals(modelid)){
    				analyzerReport.getModel().remove(model) ;
    				break;
    			}
    		}
    	}
    	
    	/**
    	 * 更新缓存
    	 */
    	updateCacheReport(request , report , analyzerReport , orgi , false) ;
    	/**
    	 * 创建视图
    	 */
    	/**
    	 * 将当期编辑的报表放入分布式缓存中，报表编辑器退出的时候需要清理该报表，同样的，在用户退出的时候，也需要清理缓存中的垃圾
    	 */
    	return createReportView(view , report , request);
   	}
    
    
    @RequestMapping(value="/desing_2" , name="desing_2" , type="design",subtype="analytics")
    public ModelAndView design2(HttpServletRequest request , @PathVariable String orgi) throws Exception{  
    	return request(super.createManageResponse("/pages/design/analytics/analyzerdesign_layout") , orgi) ;
    }
//    /**
//     * 获取报表，使用设计器打开
//     * @param request
//     * @param orgi
//     * @param reportid
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value="/{reportid}" , name="analyticsdesign" , type="design",subtype="analytics")
//    public ModelAndView reportdesign(HttpServletRequest request , @PathVariable String orgi, @PathVariable String reportid) throws Exception{  
//    	ModelAndView view = request(super.createManageResponse("/pages/design/analytics/index") , orgi) ;
//    	view.addObject("report", ReportFactory.getReportInstance().getReportByID(super.getUser(request), orgi, reportid)) ;
//    	return view ;
//    }
} 